import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Card, message, Checkbox, Space, Alert, Typography, Spin } from 'antd';
import { UserOutlined, LockOutlined, SafetyOutlined } from '@ant-design/icons';
import { useNavigate, useLocation } from 'react-router-dom';
import { loginWithJWT, isAuthenticated } from '../services/auth';
import '../styles/login.css';

const { Text, Title } = Typography;

interface LoginForm {
  username: string;
  password: string;
  remember?: boolean;
}

const Login: React.FC = () => {
  const [loading, setLoading] = useState(false);

  const [error, setError] = useState<string | null>(null);
  const [initializing, setInitializing] = useState(true);
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const location = useLocation();
  
  // 如果已经登录，重定向到仪表盘
  useEffect(() => {
    const checkAuth = async () => {
      if (isAuthenticated()) {
        navigate('/dashboard');
      } else {
        // 检查是否有记住的用户名
        const rememberedUsername = localStorage.getItem('rememberedUsername');
        if (rememberedUsername) {
          form.setFieldsValue({ username: rememberedUsername, remember: true });
        }
        setInitializing(false);
      }
    };
    
    checkAuth();
  }, [navigate, form]);

  const handleSubmit = async (values: LoginForm) => {
    try {
      setLoading(true);
      setError(null);
      
      // 记住用户名功能
      if (values.remember) {
        localStorage.setItem('rememberedUsername', values.username);
      } else {
        localStorage.removeItem('rememberedUsername');
      }
      
      // Development mode bypass
      // if (devMode) {
      //   localStorage.setItem('isAuthenticated', 'true');
      //   localStorage.setItem('user', JSON.stringify({
      //     username: values.username || 'admin',
      //     role: 'admin',
      //     displayName: '开发者模式'
      //   }));
      //   message.success('开发模式登录成功');
      //   navigate('/dashboard');
      //   return;
      // }
      
      const success = await loginWithJWT(values.username, values.password);
      
      if (success) {
        message.success('登录成功');
        // 获取重定向URL，如果没有则默认到仪表盘
        const from = location.state?.from?.pathname || '/dashboard';
        navigate(from);
      } else {
        // 登录失败，但不是网络错误等异常情况
        setError('用户名或密码错误');
      }
    } catch (error: any) {
      setError(error.message || '登录失败，请稍后重试');
      console.error('Login error:', error);
    } finally {
      setLoading(false);
    }
  };

  if (initializing) {
    return (
      <div className="login-container">
        <Spin size="large" tip="加载中..." />
      </div>
    );
  }

  return (
    <div className="login-container">
      {/* 背景动画元素 */}
      <div className="background-shapes">
        {[...Array(6)].map((_, i) => (
          <div 
            key={i}
            className="shape"
            style={{
              width: `${Math.random() * 100 + 50}px`,
              height: `${Math.random() * 100 + 50}px`,
              background: `rgba(255, 255, 255, ${Math.random() * 0.05 + 0.02})`,
              top: `${Math.random() * 100}%`,
              left: `${Math.random() * 100}%`,
              animation: `float ${Math.random() * 10 + 15}s ease-in-out infinite`,
              animationDelay: `${Math.random() * 5}s`,
            }}
          />
        ))}
      </div>

      {/* 系统标题 */}
      <div className="login-header">
        <Title className="login-title">
          <SafetyOutlined style={{ marginRight: '12px' }} />
          CangJie 遥测管理系统
        </Title>
      </div>

      <Card 
        className="glass-effect login-card"
        bodyStyle={{ padding: '32px' }}
      >
        <div style={{ textAlign: 'center', marginBottom: '24px' }}>
          <Title level={3} style={{ margin: 0, color: '#1a365d' }}>
            用户登录
          </Title>
          <Text type="secondary">请输入您的账号和密码</Text>
        </div>

        {error && (
          <Alert
            message="登录错误"
            description={error}
            type="error"
            showIcon
            closable
            className="error-alert"
            onClose={() => setError(null)}
          />
        )}
        
        <Form
          form={form}
          name="login"
          initialValues={{ remember: false }}
          onFinish={handleSubmit}
          layout="vertical"
          size="large"
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
            className="login-form-item"
          >
            <Input 
              prefix={<UserOutlined style={{ color: '#8c8c8c' }} />} 
              placeholder="用户名" 
              disabled={loading}
              autoComplete="username"
              autoFocus
              className="login-input"
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
            className="login-form-item"
          >
            <Input.Password 
              prefix={<LockOutlined style={{ color: '#8c8c8c' }} />} 
              placeholder="密码" 
              disabled={loading}
              autoComplete="current-password"
              className="login-input"
            />
          </Form.Item>
          
          <Form.Item>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Form.Item name="remember" valuePropName="checked" noStyle>
                <Checkbox disabled={loading}>记住用户名</Checkbox>
              </Form.Item>
              
              <Text 
                type="secondary" 
                className="hover-link"
                style={{ fontSize: '14px', cursor: 'pointer' }}
              >
                忘记密码?
              </Text>
            </div>
          </Form.Item>
          
          <Form.Item>
            <Space direction="vertical" style={{ width: '100%' }}>
              <Button 
                type="primary" 
                htmlType="submit" 
                loading={loading}
                className="gradient-button hover-button login-button"
              >
                登录
              </Button>
              
              {/*<div style={{ textAlign: 'center', marginTop: '8px' }}>*/}
              {/*  <Checkbox */}
              {/*    checked={devMode} */}
              {/*    onChange={(e) => setDevMode(e.target.checked)}*/}
              {/*    disabled={loading}*/}
              {/*  >*/}
              {/*    开发模式 (跳过后端验证)*/}
              {/*  </Checkbox>*/}
              {/*</div>*/}
            </Space>
          </Form.Item>
          
          <div className="login-footer">
            <Text type="secondary">© 2024 CangJie 遥测管理系统</Text>
          </div>
        </Form>
      </Card>
    </div>
  );
};

export default Login; 